<template>
  <div class="slider" ref="rootRef">
      <div class="slider-group">
          <div class="slider-page" v-for="(item, index) in sliders" :key="index">
              <a :href="item.link">
                  <img :src="item.pic" />
              </a>
          </div>
      </div>
      <div class="dots-wrapper">
          <span class="dot" v-for="(item, index) in sliders" :key="index" :class="{'active': currentPageIndex === index}"></span>
      </div>
  </div>
</template>

<script>
// ref API是vue暴露的,所以需要先引入
// ref 的作用是创建并返回一个响应式引用
import { ref } from 'vue';
import useSlider from './use-slider';
export default {
  name: 'slider',
  props: {
    sliders: {
      type: Array,
      default() {
        return [];
      }
    }
  },
  setup() {
    // 获取轮播图容器DOM元素
    const rootRef = ref(null);
    // 不能直接传入DOM元素(rootRef.value),传入的话在onMunted生命周期中拿到的是undefined,直接传ref为响应式
    const { currentPageIndex } = useSlider(rootRef);
    // 在模板中使用变量需要在setup中return出去
    return {
      rootRef,
      currentPageIndex
    };
  }
};
</script>

<style scoped lang="scss">
.slider {
    min-height: 1px;
    font-size: 0;
    touch-action: pan-y; // 启用单指水平平移手势
    .slider-group {
        position: relative;
        overflow: hidden;
        white-space: nowrap; // 连续的空白会被合并,文本内的换行无效
        .slider-page {
            display: inline-block;
            transform: translate3d(0, 0, 0); // 开启GPU硬件加速,可让网页动画更加流畅
            backface-visibility: hidden; // 元素不面向屏幕时不可见
            a {
                display: block;
                width: 100%;
            }
            img {
                display: block;
                width: 100%;
            }
        }
    }
    .dots-wrapper {
        position: absolute;
        left: 50%;
        bottom: 12px;
        line-height: 12px;
        transform: translateX(-50%);
        .dot {
            display: inline-block;
            margin: 0 4px;
            width: 8px;
            height: 8px;
            border-radius: 50%;
            background: $color-text-l;
            transition: .3s;
            transition-property: all;
            &.active {
                width: 20px;
                border-radius: 5px;
                background: $color-text-ll;
                transition: .3s;
                transition-property: all;
            }
        }
    }
}
</style>
